<?php

use Yaf\Session;
use Illuminate\Database\Capsule\Manager as Capsule;
use Rester\Validator;
use IdCard\IdCard;
use Service\App;
use Service\UserService;

class RegisterController extends BaseController
{
    public function init()
    {
        parent::init();
    }


    public function checkidAction()
    {
        $header = $this->header;
        if (!isset($header['uid'])) {
            $this->callback(['status' => 0], '0401', '未登录');
            return;
        }

        $uid = $header['uid'];

        $name = $this->getRequest()->getParam('name');
        $idNum = $this->getRequest()->getParam('id_num');
        $data = [
            'name' => $name,
            'id_num' => $idNum,
        ];
        $rules = [
            'id_num'=>'required',
            'name'=>'required'
        ];
        $validator = Validator::getInstance()->make($data, $rules);
        if ($validator->fails()) {
            $failed = $validator->failed();
            $this->callback(['status' => 0, 'info' => $failed], '0400', '参数错误');
            return;
        }

        if (!$this->checkIdLimit($uid)) {
            $this->callback(['status' => 0], '0400', '每个帐号24小时只能调' . ID5_CHECK_LIMIT . '次');
            return;
        }

        $this->callback(['status' => $this->checkId($name, $idNum)]);
        return;
    }

    protected function checkIdLimit($uid)
    {
        $redis = $this->redis;
        $key = 'id-check-limit:' . $uid . date('Y-m-d');
        $limit = $redis->incr($key);
        $redis->expire($key, 3600*24);
        if ($limit > ID5_CHECK_LIMIT) {
            return false;
        }

        return true;
    }

    protected function checkId($name, $idNum)
    {
        $idcard = new IdCard();
        if (!$idcard->isChinaIDCard($idNum)) {
            return 0;
        }
        $check = rzb($name, $idNum) ? 1 : 0;
        return $check;
    }

    public function checkphoneAction()
    {
        $phone = $this->getRequest()->getParam('phone');
        $data = [
            'phone' => $phone,
        ];
        $rules = [
            'phone'=>'required|regex:/^1[34578][0-9]{9}$/'
        ];
        $validator = Validator::getInstance()->make($data, $rules);

        if ($validator->fails()) {
            $this->callback(['status' => 0, 'info' => $validator->failed()], '0400', '手机号码错误');
            return;
        }
        $user = UserModel::query()->where(['cellphone' => $phone])->first();
        if ($user) {
            $status = 0;
        } else {
            $status = 1;
        }

        $this->callback(['status' => $status], '0000', $status == 0 ? '该手机号已注册，请直接登录':'ok');
    }

    public function createAction()
    {
        $phone = $this->getRequest()->getParam('phone');
        $code = $this->getRequest()->getParam('code');
        $pwd = $this->getRequest()->getParam('pwd');
        $type = $this->getRequest()->getParam('type');

        $data = [
            'phone' => $phone,
            'code' => $code,
            'pwd' => $pwd,
            'type' => $type,
        ];
        $rules = [
            'phone'=>'required|regex:/^1[34578][0-9]{9}$/',
            'code'=>'required|string',
            'pwd'=>'required|string',
            'type'=>'required|integer|min:1|max:2',
        ];
        $validator = Validator::getInstance()->make($data, $rules);

        if ($validator->fails()) {
            $this->callback(['info' => $validator->failed()], '0400', '参数错误');
            return;
        }
        if (UserModel::query()->where(['cellphone' => $phone])->first()) {
            $this->callback([], '0400', '用户已注册');
            return;
        }
        if (RecordPhoneModel::query()->where(['cellphone' => $phone])->first()) {
            $this->callback([], '0400', '用户已锁定');
            return;
        }
        $key = 'sms-code-register:' . $phone;
        $smsCode = $this->redis->get($key);
        if ($smsCode != $code) {
            $this->callback([], SMS_CODE_ERROR, '短信验证码输入错误');
            return;
        } else {
            $ttl = $this->redis->ttl($key);
            if ($ttl + 300 < 3600 * 24) {
                $this->callback([], SMS_CODE_ERROR, '短信验证码失效，请重新获取');
                return;
            }
            $this->redis->del($key);
        }

        $user = new UserModel();
        $user->cellphone = $phone;
        $user->pwd = $pwd;
        $user->type = $type;
        $user->id_type = $type;
        $user->add_time = time();
        $user->from_mobile = 1;
        if ($user->save()) {
            $tokeInfo = App::createToken($user->id);
            $data = [
                'token' => $tokeInfo['token'],
                'token_expire' => $tokeInfo['expire'],
            ];
            $this->callback($data);
        } else {
            $this->callback([], '0400', '注册失败');
        }
    }

    public function infoAction()
    {
        $header = $this->header;
        if (!isset($header['uid'])) {
            $this->callback(['status' => 0], '0401', '未登录');
            return;
        }

        $uid = $header['uid'];
        /** @var UserModel $user */
        $user = UserModel::query()->find($uid);
        if (!$user) {
            $this->callback(['status' => 0], '0403', '找不到用户');
            return;
        }
        if ($user->username || $user->organization_name) {
            $this->callback(['status' => 0], '0403', '该用户已认证通过');
            return;
        }

        if (!$this->checkIdLimit($uid)) {
            $this->callback(['status' => 0], '0400', '每个帐号24小时只能调' . ID5_CHECK_LIMIT . '次');
            return;
        }

        $type = $user->type;
        $data = [];

        if ($type == 1) {
            $data['name'] = $this->getRequest()->getParam('name');
            $data['id_num'] = strtoupper($this->getRequest()->getParam('id_num'));

            $name = $data['name'];
            $idCard = $data['id_num'];

            $user->username = $name;
            $user->identity_id = $idCard;

            $rules = [
                'name' => 'required|string',
                'id_num' => 'required|string',
            ];
        } else {
            $data['auth_name'] = $this->getRequest()->getParam('auth_name');
            $data['auth_id_num'] = strtoupper($this->getRequest()->getParam('auth_id_num'));
            $data['org_name'] = $this->getRequest()->getParam('org_name');
            $data['org_num'] = $this->getRequest()->getParam('org_num');
            $data['org_type'] = $this->getRequest()->getParam('org_type');
            $name = $data['auth_name'];
            $idCard = $data['auth_id_num'];

            $user->username = $name;
            $user->identity_id = $idCard;
            $user->organization_name = $data['org_name'];
            $user->business_license_number = $data['org_num'];

            $rules = [
                'auth_name' => 'required|string',
                'auth_id_num' => 'required|string',
                'org_name' => 'required|string',
                'org_num' => 'required|string',
                'org_type' => 'required|integer|min:1|max:2',
            ];
        }

        $validator = Validator::getInstance()->make($data, $rules);
        if ($validator->fails()) {
            $this->callback(['status' => 0,'info' => $validator->failed()], '0400', '参数错误');
            return;
        }
        if ($type == 2 &&
            UserModel::query()->where(['business_license_number' => $data['org_num'], 'type' => 2])->first()
        ) {
            $this->callback(['status' => 0], '0400', '营业执照号已被注册');
            return;
        }
        // 个人用户身份证绑定唯一
        if ($type == 1 && UserModel::query()->where(['identity_id' => $idCard, 'type' => 1])->first()) {
            $this->callback(['status' => 0], '0400', '用户已存在');
            return;
        }

        if (!$this->checkId($name, $idCard)) {
            $this->callback(['status' => 0], '0400', '实名认证失败，请检查输入信息');
            return;
        }

        $user->register_status = 1;
        $user->save();
        if ($type == 2) {
            $info = new OrgInfoModel();
            $info->u_id = $uid;
            $info->org_type = $data['org_type'];
            $info->name = $data['org_name'];
            $info->card = $data['org_num'];
            $info->auth_person_name = $data['auth_name'];
            $info->auth_person_card = $data['auth_id_num'];

            $info->save();
        }

        UserService::getInstance()->deleteUserInfoCache($uid);
        $this->callback(['status' => 1]);
    }
}